<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LearnVideoSectionStoreRequest;
use App\Http\Requests\QH\LearnVideoSectionExcelImportRequest;
use App\Imports\LearnVideoSectionImport;
use App\Models\LearnVideo;
use App\Models\LearnVideoChapter;
use App\Models\LearnVideoSection;
use App\Models\VideoLibrary;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Util\Exception;
use Throwable;

class LearnVideoSectionController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = LearnVideoSection::filter(\request()->all())->orderByRaw('sort asc, id asc')->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param LearnVideoSectionStoreRequest $request
     * @return JsonResponse|object
     * @throws Throwable
     */
    public function store(LearnVideoSectionStoreRequest $request)
    {
        $params = $request->validated();

        try {
            DB::beginTransaction();
            $model = LearnVideoSection::create($params);
            // 加父级数据
            $learnVideo = LearnVideo::find($model->learn_video_id);
            $learVideoChapter = LearnVideoChapter::find($model->learn_video_chapter_id);
            $learnVideo->total_second += $model->total_second;
            $learnVideo->section_count += 1;
            $learVideoChapter->total_second += $model->total_second;
            $learVideoChapter->section_count += 1;
            $learnVideo->save();
            $learVideoChapter->save();

            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            \Log::error($e);
            throw new \Exception('创建失败');
        }

        return $this->restful();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param LearnVideoSectionStoreRequest $request
     * @param int $id
     * @return JsonResponse|object
     */
    public function update(LearnVideoSectionStoreRequest $request, int $id)
    {
        $params = $request->validated();

        $result = LearnVideoSection::where('id', $id)->update($params);

        return $this->restful($result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     * @throws Throwable
     */
    public function destroy(int $id)
    {
        $result = 0;
        $model = LearnVideoSection::where('id', $id)->first();
        if ($model) {
            try {
                DB::beginTransaction();
                // 减父级数据
                $learnVideo = LearnVideo::find($model->learn_video_id);
                $learVideoChapter = LearnVideoChapter::find($model->learn_video_chapter_id);
                if($learnVideo->total_second >= $model->total_second) $learnVideo->total_second -= $model->total_second;
                else $learnVideo->total_second = 0;
                if ($learnVideo->section_count >= 1) $learnVideo->section_count -= 1;
                else $learnVideo->section_count = 0;

                if($learVideoChapter->total_second >= $model->total_second) $learVideoChapter->total_second -= $model->total_second;
                else $learVideoChapter->total_second = 0;
                if ($learVideoChapter->section_count >= 1) $learVideoChapter->section_count -= 1;
                else $learVideoChapter->section_count = 0;

                $learnVideo->save();
                $learVideoChapter->save();

                $model->delete();
                $result = 1;
                DB::commit();
            }catch (\Exception $e) {
                DB::rollBack();
            }
        }

        return $this->restful($result);
    }

    public function getOptions()
    {
        $list = LearnVideoSection::select(['id as value', 'name as label'])->get()->toArray();

        return $this->restful($list);
    }

    /**
     * @return JsonResponse|object
     * @throws Throwable
     */
    public function storeByVideoId()
    {
        $params = \request()->validate([
            'name' => 'bail|nullable|string',
            'video_ids' => 'bail|required|array',
            'learn_video_id' => 'bail|required|int',
            'learn_video_chapter_id' => 'bail|required|int',
        ], \request()->all());


        $videos = VideoLibrary::whereIn('id', $params['video_ids'])->get();

        // 获取小节下最后一个排序值
        $lastSort = LearnVideoSection::where('learn_video_id', $params['learn_video_id'])
            ->where('learn_video_chapter_id', $params['learn_video_chapter_id'])
            ->orderByDesc('sort')
            ->value('sort') ?? 1;

        DB::beginTransaction();

        try {
            $successCount = 0;
            $successSecond = 0;
            foreach ($videos as $video) {
                $lastSort += 1;
                $_model = LearnVideoSection::create([
                    'learn_video_id' => $params['learn_video_id'],
                    'learn_video_chapter_id' => $params['learn_video_chapter_id'],
                    'name' => $video->name,
                    'total_size' => $video->total_size,
                    'total_second' => $video->total_second,
                    'video_format' => $video->video_format,
                    'video_url' => $video->video_url,
                    'thumb' => $video->thumb,
                    'sort' => $lastSort
                ]);
                $successCount += 1;
                $successSecond += $_model->total_second;
            }

            // 加父级数据
            $learVideoChapter = LearnVideoChapter::find($params['learn_video_chapter_id']);
            if ($learVideoChapter) {
                $learVideoChapter->total_second += $successSecond;
                $learVideoChapter->section_count += $successCount;
                $learVideoChapter->save();
            }

            $learnVideo = LearnVideo::find($params['learn_video_id']);
            if ($learnVideo) {
                $learnVideo->total_second += $successSecond;
                $learnVideo->section_count += $successCount;
                $learnVideo->save();
            }

            DB::commit();
        }catch (\Exception $e) {
            \Log::error($e);
            DB::rollBack();
            throw new \Exception('创建失败');
        }


        return $this->restful();
    }

    /**
     * 导入小节excel
     * @param LearnVideoSectionExcelImportRequest $request
     * @return JsonResponse|object
     */
    public function storeByExcel(LearnVideoSectionExcelImportRequest $request)
    {
        $params = $request->validated();

        Excel::import(new LearnVideoSectionImport($params['learnVideoId'], $params['learnVideoChapterId']), $params['file']);

        return $this->restful();
    }
}
